package com.wangp.mywrite.s_juc.lock.readwrite;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author farling-wangp
 * @version 1.0
 * @date 2020/9/26 21:54
 */
public class Upgrading {
    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private static ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
    private static ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();

    private static void readUpgrading() {
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "得到了readLock,正在读取");
            Thread.sleep(1000);
            System.out.println("升级会带来阻塞");
            writeLock.lock();
            System.out.println("获取到了写锁，升级成功");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + "释放了readLock");
            readLock.unlock();
        }
    }

    private static void writeDowngrading() {
        writeLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "得到了writeLock,正在写入");
            Thread.sleep(1000);
            readLock.lock();
            System.out.println("在不释放写锁的情况下直接获取读锁，成功降级");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readLock.lock();
            System.out.println(Thread.currentThread().getName() + "释放了writeLock");
            writeLock.unlock();
        }
    }

    public static void main(String[] args) {
        System.out.println("降级");
        new Thread(() -> writeDowngrading(), "thread1").start();
        System.out.println("----------------------");
        System.out.println("升级");
        new Thread(() -> readUpgrading(), "thread2").start();
    }
}
